package com.sunshine.wrongquestionset.activity.main

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager2.widget.ViewPager2

import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.activity.add_question.AddQuestionActivity
import com.sunshine.wrongquestionset.activity.base.BaseActivity
import com.sunshine.wrongquestionset.activity.exercise.ExerciseActivity
import com.sunshine.wrongquestionset.activity.settings.SettingActivity
import com.sunshine.wrongquestionset.callback.OnRefreshListener
import com.sunshine.wrongquestionset.room.entity.AppConfigEntity
import com.sunshine.wrongquestionset.room.entity.QuestionEntity
import com.sunshine.wrongquestionset.room.entity.SubjectEntity
import com.sunshine.wrongquestionset.utils.AnalyzerUtils
import com.sunshine.wrongquestionset.utils.FamiliarityBean
import com.sunshine.wrongquestionset.utils.FamiliarityUtils
import com.sunshine.wrongquestionset.utils.TimeUtils
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : BaseActivity() {

    private lateinit var viewModel: MainViewModel

    private val onPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
            //设置底栏高亮
            bottomNavigationView.menu.getItem(position).isChecked = true

//            if (position == 1) {
//                //setActionBarVisibility(false)
//                //setSupportActionBar(toolbarSearch)
//            } else {
//                //setActionBarVisibility(true)
//                //setSupportActionBar(toolbar)
//            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentViewWithoutDisplayHomeAsUp(R.layout.activity_main)
        setTitle(getString(R.string.label_main))

        viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(application)).get(MainViewModel::class.java)

        viewPager.adapter = FragmentAdapter(this)
        viewPager.registerOnPageChangeCallback(onPageChangeCallback)

        bottomNavigationView.setOnNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.home -> viewPager.currentItem = 0
                R.id.search -> viewPager.currentItem = 1
                R.id.analysis -> viewPager.currentItem = 2
                R.id.me -> viewPager.currentItem = 3
            }
            true
        }

        updateStartTime()
    }

    /**
     * 更新启动时间，如果启动时间大于上次启动时间1天，就要对遗忘曲线进行刷新
     */
    private fun updateStartTime() {
        getLoginUserAppConfig(object : OnRefreshListener<AppConfigEntity>() {
            override fun onUpdate(obj: AppConfigEntity) {
                super.onUpdate(obj)

                //如果距离上次启动时间大于1天，就要更新遗忘曲线
                val nowDate = Date().time
                val dateDifference = TimeUtils.dateDifference(obj.lastStartTime, nowDate)
                if (dateDifference > 0) {
                    val allUserQuestionLiveData = viewModel.getAllUserQuestion()
                    allUserQuestionLiveData.observe(this@MainActivity, Observer {
                        val familiarityList: ArrayList<FamiliarityBean> = FamiliarityUtils.reduceFamiliarity(it, dateDifference)

                        familiarityList.forEach {familiarityBean ->
                            //刷新问题中的熟悉程度
                            viewModel.refreshFamiliarity(familiarityBean.questionId, familiarityBean.familiarity)

                            //插入一条新的题目信息项
                            viewModel.insertQuestionInfo(familiarityBean.questionId, familiarityBean.familiarity)
                        }

                        allUserQuestionLiveData.removeObservers(this@MainActivity)
                    })

                    //刷新数据库
                    obj.lastStartTime = nowDate
                    viewModel.updateAppConfig(obj)
                }
            }
        })
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.setting -> {
                startActivity(Intent(this, SettingActivity::class.java))
            }
            R.id.add_question -> {
                startActivity(Intent(this, AddQuestionActivity::class.java))
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onDestroy() {
        super.onDestroy()
        viewPager.unregisterOnPageChangeCallback(onPageChangeCallback)
    }
}